package com.example;

import java.io.File;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;

public class FileExtension {
    /**
     * 文件转为base64字符串
     *
     * @param filePath 文件路径
     * @return 转换后的base64字符串
     * @throws Exception 文件路径不正确时触发IllegalArgumentException；文件不存在时触发FileNotFoundException
     */
    public String toBase64(String filePath) throws Exception {
        if (filePath == null || filePath.isBlank()) {
            throw new IllegalArgumentException("文件路径错误");
        }

        File file = new File(filePath);

        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在");
        }

        byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
        String result = Base64.getEncoder().encodeToString(fileBytes);

        //模拟网络传输的字符串编码
        if (result != null && !result.isBlank()) {
            result = result.replace("+", "%2b");
        }

        return result;
    }

    /**
     * base64字符串还原为文件
     * @param base64 文件转换后的base64字符串
     * @param filePath 文件完整存储路径，例如 /home/bob/test.txt
     * @throws Exception 当传入的base64字符串为空时触发IllegalArgumentException；当文件路径不正确时触发IllegalArgumentException；当文件不存在时触发FileNotFoundException
     */
    public void fromBase64(String base64, String filePath) throws Exception {
        if (base64.isBlank()) {
            throw new IllegalArgumentException("传入的base64无效");
        }
        if (filePath.isBlank()) {
            throw new IllegalArgumentException("文件路径错误");
        }

        File file = new File(filePath);

        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在");
        }

        Files.write(Paths.get(filePath), Base64.getDecoder().decode(base64.replace("%2b", "+")), StandardOpenOption.CREATE);
    }
}